<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示标签 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="form"
        ref="formRef"
        :rules="formRules"
        label-width="100px"
        label-position="top"
      >
        <!-- tab栏 -->
        <!-- 注释掉el-tabs的@tab-click="tabClick" -->
        <el-tabs
          v-model="active"
          tab-position="left"
          :before-leave="before"
          
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="form.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="form.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="form.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="form.goods_cat"
                clearable
                :options="cateList"
                :props="propsConfig"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(jtem, index) in item.attr_vals"
                  :key="index"
                  :label="jtem"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="att.attr_name"
              v-for="att in onlyData"
              :key="att.attr_id"
            >
              <el-input v-model="att.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action: 图片要上传到的api地址 -->
            <el-upload
              :action="uploadURL"
              :headers="headerObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="form.goods_introduce"></quill-editor>
            <el-button class="btn" type="primary" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog
      title="图片预览"
      :visible.sync="preDialogVisible"
      width="50%"
      @close="clearUrl"
    >
      <img :src="previewPath" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "0",
      form: {
        goods_name: undefined,
        goods_price: undefined,
        goods_weight: undefined,
        goods_number: undefined,
        // 商品所属的分类数组
        goods_cat: [],
        // 图片数组
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      formRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      cateList: [],
      propsConfig: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyData: [],
      onlyData: [],
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPath: "",
      preDialogVisible: false,
    };
  },
  methods: {
    handSuccess(res) {
      if (res.meta.status !== 200) {
        return this.$message.error("上传失败");
      }
      const picsInfo = { pic: res.data.tmp_path };
      this.form.pics.push(picsInfo);
    },
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.form.pics.findIndex((x) => x.pic === filePath);
      this.form.pics.splice(i, 1);
    },
    handlePreview(file) {
      this.preDialogVisible = true;
      this.previewPath = file.response.data.url;
    },
    clearUrl() {
      this.previewPath = "";
      this.preDialogVisible = false;
    },
    async getList() {
      const { data: res } = await this.$http.get("categories");
      this.cateList = res.data;
    },
    // tabClick() {
    //   if (this.active === "1") {
    //     this.getParams("many");
    //   } else if (this.active === "2") {
    //     this.getParams("only");
    //   } else {
    //     return;
    //   }
    // },
    async getParams(sels) {
      const { data: res } = await this.$http.get(
        `categories/${this.form.goods_cat[2]}/attributes`,
        { params: { sel: sels } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      if (sels === "many") {
        res.data.forEach((item) => {
          item.attr_vals.length === 0
            ? []
            : (item.attr_vals = item.attr_vals.split(","));
        });
        this.manyData = res.data;
      } else {
        this.onlyData = res.data;
      }
    },
    handleChange() {
      this.manyData = [];
      this.onlyData = [];
      this.getParams("only");
      this.getParams("many");
      if (this.form.goods_cat.length !== 3) {
        this.form.goods_cat = [];
      }
    },
    before(active, oldActive) {
      if (oldActive === "0" && this.form.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    add() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        }
        let deepCopy = JSON.parse(JSON.stringify(this.form));
        deepCopy.goods_cat = deepCopy.goods_cat.join(",");
        this.manyData.forEach((item) => {
          if (item.attr_vals === "") {
            const newArr = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
            deepCopy.attrs.push(newArr);
          } else {
            const newArr = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(","),
            };
            deepCopy.attrs.push(newArr);
          }
        });
        this.onlyData.forEach((item) => {
          const newArr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          deepCopy.attrs.push(newArr);
        });
        const { data: res } = await this.$http.post("goods", deepCopy);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("创建商品成功");
        this.$router.push("/goods");
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="less" scoped>
.el-tabs {
  margin-top: 15px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.btn {
  margin-top: 15px;
}
</style>